import { defineEventHandler, readBody } from 'h3'
import { getPool } from '../../util/mysql'
import { checkAdminKey } from './_utils'

function now() { return new Date() }

export default defineEventHandler(async (event: any) => {
  const ck = await checkAdminKey(event)
  if (!ck.ok) return { status: event.node.res.statusCode || 401, message: ck.message }

  const body = await readBody(event).catch(() => ({}))
  const id = body.id
  if (!id) {
    event.node.res.statusCode = 400
    return { status: 400, message: 'id required' }
  }

  try {
    const pool = await getPool()
    const deleter_id = 0
    const deletion_time = now()
    await pool.execute(`UPDATE lin_product SET is_deleted = 1, deleter_id = ?, deletion_time = ? WHERE id = ?`, [deleter_id, deletion_time, id])
    return { ok: true }
  } catch (err: any) {
    event.node.res.statusCode = 500
    const res: any = { status: 500, message: String(err?.message || err) }
    if (process.env.NODE_ENV !== 'production') res.stack = err?.stack
    return res
  }
})
